package com.dk.academic.config;

import com.dk.academic.config.realm.CustomRealm;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: 廉雪峰
 * @Date: 2019/1/10 15:46
 * @Version 1.0
 */
@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必须设置SecurityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // serLoginUrl如果不设置值，默认会自动寻找web工程根目录下的"/login.html"
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 设置无权限时跳转的url
        shiroFilterFactoryBean.setUnauthorizedUrl("/notRole");

        // 设置拦截器
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        // 游客，开放权限
        //filterChainDefinitionMap.put("/guest/**", "anon");
        // 用户，需要角色权限 customer
        filterChainDefinitionMap.put("/user/**", "roles[customer]");
        // 管理员，需要角色权限admin
        filterChainDefinitionMap.put("/admin/**", "roles[admin]");
        // 开放登录接口
        filterChainDefinitionMap.put("/login", "anon");
        // 其余接口一律拦截
        // 主要这行代码必须放在所有权限设置的最后，不然会导致所有的url均被拦截
        //filterChainDefinitionMap.put("/**", "authc");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        System.out.println("Shiro拦截器工厂类注入成功");
        return shiroFilterFactoryBean;

    }

    /*
        注入securityManager
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置realm
        securityManager.setRealm(customRealm());
        return securityManager;
    }

    /*
        自定义身份认证realm
        必须写这个类，加上bean注解，目的是注入CustomRealm
        否则会影响CustomRealm类中其他类的依赖注入
     */
    public CustomRealm customRealm() {
        return new CustomRealm();
    }
}
